/*************************************************************************
 * File Name:    Rotate_List.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/17 22:02:55
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Rotate List
 |
 | Given a list, rotate the list to the right by k places, where k is non-negative.
 |
 | For example:
 | Given 1->2->3->4->5->NULL and k = 2,
 | return 4->5->1->2->3->NULL.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k)
    {
        if (head == NULL || k == 0) return head;
        ListNode *p;
        
        int elem_cnt = 1;
        for (p = head; p->next != NULL; p = p->next) {
            ++elem_cnt;
        }
        k %= elem_cnt;
        if (k == 0) return head;
        p->next = head;
        
        p = head;
        for (int i = 1; i < elem_cnt - k; ++i) {
            p = p->next;
        }
        ListNode *ans = p->next;
        p->next = NULL;
        return ans;
    }
};

